package com.xinqi.modules.exam.common.delayed;

import com.xinqi.common.rocketmq.util.ByteUtils;
import com.xinqi.common.rocketmq.util.MqHelpUtils;
import com.xinqi.modules.exam.common.delayed.dto.ExamMqMessage;
import com.xinqi.modules.exam.common.enums.ExamQueueEnum;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.apis.ClientException;
import org.apache.rocketmq.client.apis.ClientServiceProvider;
import org.apache.rocketmq.client.apis.message.MessageBuilder;
import org.apache.rocketmq.client.apis.producer.Producer;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * 测评主题事件服务
 *
 * @author linkai
 * @date 2023/7/7
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class ExamTopicEventService {
    private final ExamDelayQueueService examDelayQueueService;
    @Qualifier("defaultProducer")
    private final Producer producer;

    @Value("${rocketmq.examTopic}")
    public String examTopic;

    /**
     * 发布事件
     *
     * @param examQueue 主题
     * @param examId    测评ID
     */
    public void publishEvent(ExamQueueEnum examQueue, Long examId) {
        String key = examDelayQueueService.mqId(examQueue, examId);
        String tag = examQueue.queueName();
        String body = ExamMqMessage.as(examQueue.queueName(), examId.toString());
        log.info("发送普通消息，topic = {}, key = {}, tag = {}, body = {}", examTopic, tag, key, body);
        ClientServiceProvider provider = MqHelpUtils.provider();
        MessageBuilder messageBuilder = provider.newMessageBuilder();
        messageBuilder
            .setTopic(examTopic)
            .setKeys(key)
            .setTag(tag)
            .setBody(ByteUtils.str2Byte(body));
        try {
            producer.send(messageBuilder.build());
        } catch (ClientException e) {
            log.error("发送普通消息-失败，topic = {}, key = {}, tag = {}, body = {}", examTopic, tag, key, body, e);
            throw new RuntimeException(e);
        }

    }

}
